package com.gientech.group9.controller;


import com.gientech.group9.controller.*;
import com.gientech.group9.entity.User;
import com.gientech.group9.entity.response.ApiResponse;
import com.gientech.group9.entity.User;
import com.gientech.group9.entity.response.ApiResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/login")
public class LoginController {

    //用户列表
    private final static List<User> userList = new ArrayList<>();

    static {
        User user1 = new User("customer",1,"user1","123456","用户1");
        User user2 = new User("customer",2,"user2","123456","用户2");
        User user3 = new User("customer",3,"user3","123456","用户3");
        User user4 = new User("auditor1",4,"auditor1","123456","auditor1");
        User user5 = new User("auditor2",5,"auditor2","123456","auditor2");
        User user6 = new User("auditor3",6,"auditor3","123456","auditor3");
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);
        userList.add(user5);
        userList.add(user6);
    }


    /**
     * 登陆
     * @param loginUser 用户实体
     * @return
     */
    @PostMapping("/login")
    public  ApiResponse login(@RequestBody User loginUser, HttpServletRequest request){
        if(loginUser == null || StringUtils.isBlank(loginUser.getUsername()) || StringUtils.isBlank(loginUser.getPassword())){
            return ApiResponse.error("请输入账号或密码");
        }

        for (User user : userList) {
            if(user.equals(loginUser)){
                String requestedSessionId = request.getRequestedSessionId();
                HttpSession session = request.getSession();
                session.setAttribute("userInfo",user);
                return ApiResponse.success(200,"登录成功",user);
            }
        }
        return ApiResponse.error("帐号或密码错误");

    }


    /**
     * 退出按钮 - 直接让前端跳转到登录页面
     */




}
